package com.apptravel.web.controller.admin;

import com.apptravel.dao.AdminDAO;
import com.apptravel.entity.Admin;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.apptravel.util.Constants;

import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2012-1-17
 * Time: 10:43:50
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class AdminLoginController {

    private static final String LOGOUT = "/logout";

    private static final String LOGIN_VIEW = "admin/login";

    @Autowired
    private AdminDAO adminDao;

    /**
     * 登录页.
     *
     * @return
     */
    @RequestMapping(Constants.LOGIN_URL)
    public String login(String code, ModelMap model){
        model.put("code",code);
        return LOGIN_VIEW;
    }


    @RequestMapping(Constants.LOGON_URL)
    public String logon(String username,String password, HttpSession session){
        Admin admin = adminDao.selectByName(username);
        if(admin == null){
           return "redirect:"+Constants.LOGIN_URL+"?code=-1";
        }else{
            String pwdmd5 = DigestUtils.md5Hex(password);
            if(!pwdmd5.equals(admin.getUserpwd())){
               return "redirect:"+Constants.LOGIN_URL+"?code=-2";
            }
        }
        session.setAttribute(Constants.ADMIN_IN_SESSION,admin);
        return "redirect:"+Constants.HOME_URL;
    }

    /**
     *
     * @param session
     * @return
     */
    @RequestMapping(LOGOUT)
    public String logout(HttpSession session){
       session.invalidate();
       return "redirect:"+Constants.HOME_URL;
    }
}
